﻿using Microsoft.VisualBasic;
using MobileControlGuru.Src;
using Newtonsoft.Json;
using Quartz;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.UI.WebControls;
using System.Windows.Forms;
using System.Xml.Linq;
using static MobileControlGuru.AutoTask.TaskJson;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;

namespace MobileControlGuru.AutoTask
{
    public partial class TaskEdit : BaseForm
    {

        public TaskJson.TaskInfo taskInfo;

        public TaskEdit()
        {
            InitializeComponent();

        }

        public TaskEdit(TaskJson.TaskInfo taskInfo)
        {

            this.taskInfo = taskInfo;
            InitializeComponent();
        }
        private void TaskEdit_Load(object sender, EventArgs e)
        {
            this.dateTimePickerEnd.Format = DateTimePickerFormat.Time;


            this.dateTimePickerStart.Format = DateTimePickerFormat.Time;
            this.inputNumberWorkTime.Text = "90";
            //foreach (var d in DeviceManager.Instance.devices)
            //{


            //    this.selectMultipleDevice.Items.Add(d.Name);
            //    Console.WriteLine(d.Name);
            //}
            this.InitCheckBoxDevice();
            if (taskInfo != null)
            {
                this.inputTaskName.Text = taskInfo.Name;
                if (!string.IsNullOrEmpty(taskInfo.Corn))
                    this.inputCorn.Text = taskInfo.Corn;

                //设置显示已保存的设备
                //this.selectMultipleDevice.SelectedValue = taskInfo.DeviceName;
                if (taskInfo.TaskItems != null)
                    InitTaskItems(taskInfo.TaskItems);
                if (taskInfo.StartDeteTime != null)
                {

                    this.dateTimePickerStart.Value = (DateTime)taskInfo.StartDeteTime;

                }
                if (taskInfo.EndDeteTime != null)
                {

                    this.dateTimePickerEnd.Value = (DateTime)taskInfo.EndDeteTime;
                }

                this.comboBoxType.SelectedIndex = taskInfo.Type.GetHashCode();
                ChangeTaskType();
                InitCheckBoxDeviceItemChecked();
            }
            else
            {
                if (this.comboBoxType.SelectedIndex == 0)
                {
                    //this.dateTimePickerStart.Value = DateTime.Now.AddSeconds(30);
                    //this.dateTimePickerEnd.Value = this.dateTimePickerStart.Value.AddMinutes(2);
                    int count_device = DeviceManager.Instance.devices.Count;
                    //DateTime? starttime = TaskJson.GetLatestEndDateTime(TaskJson.Instance.tasks);
                    //if (starttime != null)
                    //{
                    //    DateTime dt = (DateTime)starttime;
                    //    this.dateTimePickerStart.Value = dt.AddMinutes(2);
                    //    this.dateTimePickerEnd.Value = dt.AddMinutes(count_device * 2);
                    //}
                    //else
                    //{
                    //    this.dateTimePickerStart.Value = DateTime.Now.AddMinutes(3);
                    //    this.dateTimePickerEnd.Value = DateTime.Now.AddMinutes(count_device * 2);
                    //}
                    this.dateTimePickerStart.Value = DateTime.Now.AddMinutes(2);
                    this.dateTimePickerEnd.Value = DateTime.Now.AddMinutes(count_device * 2);
                }



            }



        }

        private void InitTaskItems(List<TaskItem> taskItems)
        {
            foreach (var item in taskItems)
            {
                var edit = new TaskEditItem(item);
                edit.deleteEevnt += ItemDelete;
                this.flowLayoutPanel1.Controls.Add(edit);
            }

        }
        private void InitCheckBoxDevice()
        {
            foreach (var d in DeviceManager.Instance.devices)
            {

                this.checkedListBoxDevice.Items.Add(d.Name);

                Console.WriteLine(d.Name);
            }



        }
        private void InitCheckBoxDeviceItemChecked()
        {
            for (int i = 0; i < this.checkedListBoxDevice.Items.Count; i++)
            {
                if (taskInfo.DeviceName != null)
                    foreach (var item in taskInfo.DeviceName)
                    {
                        if (this.checkedListBoxDevice.Items[i].ToString() == item)
                        {
                            this.checkedListBoxDevice.SetItemChecked(i, true);
                        }
                    }
            }
        }
        // 全选按钮的点击事件
        private void btnCheckAll_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < this.checkedListBoxDevice.Items.Count; i++)
            {
                this.checkedListBoxDevice.SetItemChecked(i, true);
            }
        }

        // 全不选按钮的点击事件
        private void btnUnCheckAll_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < this.checkedListBoxDevice.Items.Count; i++)
            {
                this.checkedListBoxDevice.SetItemChecked(i, false);
            }
        }

        private string[] GetCheckedDevices()
        {
            List<string> Devices = new List<string>();
            // 通过遍历获取选中的项
            foreach (string item in this.checkedListBoxDevice.CheckedItems)
            {
                Devices.Add(item);
                Console.WriteLine(item);
            }

            return Devices.ToArray();
        }
        private int[] GetCheckedItemIndexs()
        {
            List<int> itemIndexs = new List<int>();
            // 通过索引获取选中的项
            for (int i = 0; i < this.checkedListBoxDevice.CheckedIndices.Count; i++)
            {
                int index = this.checkedListBoxDevice.CheckedIndices[i];
                Console.WriteLine(this.checkedListBoxDevice.Items[index]);

                itemIndexs.Add(index);
            }
            return itemIndexs.ToArray();
        }
        private void Init()
        {



        }


        private void UpdateItemIndex()
        {
            int i = 0;
            foreach (TaskEditItem c in this.flowLayoutPanel1.Controls)
            {
                c.SetIndex(++i);
            }
        }
        private void button3_Click(object sender, EventArgs e)
        {
            this.flowLayoutPanel1.Controls.Clear();
        }


        private List<TaskJson.TaskItem> GetTaskItems()
        {
            List<TaskJson.TaskItem> list = new List<TaskJson.TaskItem>();

            foreach (TaskEditItem c in this.flowLayoutPanel1.Controls)
            {
                list.Add(c.GetTaskInfo());
            }
            return list;
        }

        public TaskJson.TaskInfo GetTaksInfo()
        {

            List<TaskJson.TaskItem> list = this.GetTaskItems();
            if (taskInfo != null)
            {
                taskInfo.TaskItems = list;
                if (!string.IsNullOrEmpty(this.inputCorn.Text))
                    taskInfo.Corn = this.inputCorn.Text;


                taskInfo.DeviceName = GetCheckedDevices();

                taskInfo.Name = this.inputTaskName.Text;
                taskInfo.StartDeteTime = this.dateTimePickerStart.Value;
                taskInfo.EndDeteTime = this.dateTimePickerEnd.Value;
                return taskInfo;
            }
            else
            {
                return new TaskJson.TaskInfo()
                {
                    Name = string.IsNullOrEmpty(this.inputTaskName.Text) ? DateTime.Now.ToString("yyyyMMddHHmmss") : this.inputTaskName.Text + "-" + DateTime.Now.ToString("yyyyMMddHHmmss"),
                    Corn = this.inputCorn.Text,
                    DeviceName = GetCheckedDevices(),
                    TaskItems = list
                };
            }

        }


        public void ItemDelete(int index)
        {
            UpdateItemIndex();
        }


        SelectDevice selectDevice;
        private void button4_Click(object sender, EventArgs e)
        {

            selectDevice = new SelectDevice();
            selectDevice.button1.Click += SureDevice;
            selectDevice.ShowDialog(this);



        }
        private void SureDevice(object sender, EventArgs e)
        {
            foreach (var item in this.selectDevice.selectMultipleDevice.SelectedValue)
            {
                TaskRunWindow tr = new TaskRunWindow(item.ToString(), GetTaksInfo(), true);
                tr.Text = "debug on:" + item;
                tr.ShowDialog(this);
            }

            selectDevice.Dispose();

        }

        private void buttonAdd_Click(object sender, EventArgs e)
        {
            var edit = new TaskEditItem();
            edit.deleteEevnt += ItemDelete;

            this.flowLayoutPanel1.Controls.Add(edit);
            UpdateItemIndex();
        }

        private void buttonCornHelp_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("https://www.pppet.net");

        }

        private void btnSaveTask_Click(object sender, EventArgs e)
        {
            var t = GetTaksInfo();
            if (string.IsNullOrEmpty(t.Name))
            {
                MessageBox.Show("任务名称必填");
            }
            if (t.DeviceName == null)
            {
                MessageBox.Show("未选中任何设备");
            }
            if (this.comboBoxType.SelectedIndex == 0)
            {
                t.Type = TaskTypeEnum.datetime;
                t.Corn = null;
            }
            else if (this.comboBoxType.SelectedIndex == 1)
            {
                //if(string.IsNullOrEmpty(t.Corn))
                //{
                //    MessageBox.Show("Corn 必填");

                //    return;
                //}
                //bool isValid = CronExpression.IsValidExpression(t.Corn);
                ////如果isValid为true，则表示Cron表达式是有效的；如果为false，则表示Cron表达式有误。
                //if (!isValid)
                //{
                //    MessageBox.Show("Corn 表达式有误");

                //    return;
                //}
                t.Type = TaskTypeEnum.corn;
                t.StartDeteTime = null;
                t.EndDeteTime = null;
            }
            if (t.id == 0)
            {
                TaskJson.AddTask(t);
            }
            else
            {
                TaskJson.EditTask(t);
            }
            this.Close();
        }
        #region 按设备随机分配任务
        private void btnRandomTask_Click(object sender, EventArgs e)
        {

            DateTime starttime = this.dateTimePickerStart.Value;
            DateTime endtime = this.dateTimePickerEnd.Value;

            string[] devicenames = GetCheckedDevices();
            string tempworkcontent = String.Join(",", devicenames);
            List<ScheduleDevice> selectDevices = new List<ScheduleDevice>();
            foreach (var item in devicenames)
            {
                ScheduleDevice d = new ScheduleDevice();
                d.Name = item;
                d.WorkContent = tempworkcontent;
                selectDevices.Add(d);
            }

            List<TaskJson.TaskItem> list = this.GetTaskItems();

            if (!string.IsNullOrEmpty(this.inputNumberWorkTime.Text))
            {
                Random random = new Random();
                TaskJson.TaskRandom(starttime, endtime, selectDevices, list, random,null, Convert.ToInt32(this.inputNumberWorkTime.Text));
            }




            this.Close();
        }
        #endregion

        private void btnExportTaskItem_Click(object sender, EventArgs e)
        {
            List<TaskJson.TaskItem> list = this.GetTaskItems();
            // 序列化数据到JSON字符串
            string jsonData = JsonConvert.SerializeObject(list, Formatting.Indented);
            // 创建SaveFileDialog实例并配置
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = "JSON (*.json)|*.json|所有文件 (*.*)|*.*";
            saveFileDialog.Title = "导出数据";
            saveFileDialog.FileName = $"导出操作步骤_{DateTime.Now.ToString("yyyyMMddHHmmss")}"; // 默认文件名

            // 显示保存对话框并获取用户选择
            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {


                try
                {
                    File.WriteAllText(saveFileDialog.FileName, jsonData);

                    MessageBox.Show("数据导出成功！");
                }
                catch (Exception ex)
                {
                    // 处理文件写入过程中的异常
                    MessageBox.Show($"导出失败：{ex.Message}");
                }
            }
        }

        private void btnImportTaskItem_Click(object sender, EventArgs e)
        {
            // 使用OpenFileDialog让用户选择JSON文件
            OpenFileDialog openFileDialog = new OpenFileDialog
            {
                Filter = "JSON files (*.json)|*.json",
                DefaultExt = "json"
            };

            // 如果用户选择了文件并点击了“打开”
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    // 读取JSON文件的内容
                    string jsonFilePath = openFileDialog.FileName;
                    string jsonData = File.ReadAllText(jsonFilePath);

                    // 反序列化JSON字符串到对象列表
                    List<TaskItem> dataList = JsonConvert.DeserializeObject<List<TaskItem>>(jsonData);

                    // 使用dataList中的数据
                    // 例如，将其显示在DataGridView或其他控件中
                    InitTaskItems(dataList);
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"导入失败：{ex.Message}");
                }
            }
        }

        private void comboBoxType_SelectedIndexChanged(object sender, EventArgs e)
        {
            // 检查是否有选中项
            if (comboBoxType.SelectedIndex != -1)
            {
                // 获取选中项
                var selectedItem = comboBoxType.SelectedItem;
                // 执行基于选中项的逻辑
                //MessageBox.Show($"选中的项是：{selectedItem}");

                this.ChangeTaskType();
            }
        }

        public void ChangeTaskType()
        {
            if (comboBoxType.SelectedIndex == 0)
            {
                this.flowLayoutPanelCorn.Visible = false;
                this.flowLayoutPanelDate.Visible = true;
                if (this.taskInfo != null)
                    this.taskInfo.Type = TaskTypeEnum.datetime;
            }
            if (comboBoxType.SelectedIndex == 1)
            {
                this.flowLayoutPanelCorn.Visible = true;
                this.flowLayoutPanelDate.Visible = false;
                if (this.taskInfo != null)
                    this.taskInfo.Type = TaskTypeEnum.corn;
            }
        }


    }
}
